package com.red.wine.view;

import com.red.wine.util.StringUtil;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
/**
 * 大图
 * @author yhl
 * TODO
 * 2013-10-11上午9:54:10
 * {@link description}
 */
public class RotatView extends ImageView {
	/**
	 * 原心坐标x
	 */
	float o_x;
	/**
	 * 原心坐标y
	 */
	float o_y;

	/**
	 * 图片的宽度
	 */
	int width;

	/**
	 * 图片的高度
	 */
	int height;

	/**
	 * 旋转的图片
	 */
	Bitmap rotatBitmap;
	private Handler handlers;
	private int tilt;

	public RotatView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
		 
	}

	public RotatView(Context context, int px, int py, int id, Handler handlers, int tilt) {
		super(context);
		rotatBitmap = BitmapFactory.decodeResource(getResources(), id);
		this.tilt = tilt;
		this.o_x = px;
		this.handlers = handlers;
		this.o_y = py;
		init();
	}

	private void init() {
		initSize();
	}

	public void setRotatBitmap(Bitmap bitmap) {
		rotatBitmap = bitmap;
		initSize();
		postInvalidate();
	}

	private void initSize() {
		if (rotatBitmap == null) {
			return;
		}
		width = rotatBitmap.getWidth();
		height = rotatBitmap.getHeight();
	}

	/**
	 * 通过此方法来控制旋转度数，如果超过360，让它求余，防止，该值过大造成越界
	 * 
	 * @param added
	 */
	private void addDegree(float added) {
		deta_degree += added;
		if (deta_degree > 360 || deta_degree < -360) {
			deta_degree = deta_degree % 360;
		}
	}

	@Override
	protected void onDraw(Canvas canvas) {

		Matrix matrix = new Matrix();
		// 设置转轴位置
		matrix.setTranslate((float) width / 2, (float) height / 2);

		// 开始转
		matrix.preRotate(deta_degree);
		
		// 转轴还原
		matrix.preTranslate(-(float) width / 2, -(float) height / 2);

		// 将位置送到view的中心
		matrix.postTranslate((float) o_x - width / 2, (float) o_y - height / 2);

//		canvas.drawBitmap(rotatBitmap, matrix, paint);
		super.onDraw(canvas);
	}

	Paint paint = new Paint();

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		// 它的宽高不是图片的宽高，而是以宽高为直角的矩形的对角线的长度
		setMeasuredDimension((int) width, (int) heightMeasureSpec);

	}

	/**
	 * 手指触屏的初始x的坐标
	 */
	float down_x;

	/**
	 * 手指触屏的初始y的坐标
	 */
	float down_y;

	/**
	 * 移动时的x的坐标
	 */
	float target_x;

	/**
	 * 移动时的y的坐标
	 */
	float target_y;

	/**
	 * 放手时的x的坐标
	 */
	float up_x;

	/**
	 * 放手时的y的坐标
	 */
	float up_y;

	/**
	 * 当前的弧度(以该 view 的中心为圆点)
	 */
	float current_degree;

	/**
	 * 放手时的弧度(以该 view 的中心为圆点)
	 */
	float up_degree;

	/**
	 * 当前圆盘所转的弧度(以该 view 的中心为圆点)
	 */
	float deta_degree;

	/**
	 * 旋转速度(度/毫秒)
	 */
	double speed = 0.01;

	/**
	 * 是否为顺时针旋转
	 */
	boolean isClockWise;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (rotatBitmap == null) {
			throw new NoBitMapError("Error,No bitmap in RotatView!");
		}
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN: {//按下
			down_x = event.getX();
			down_y = event.getY();
//			double tilts = Math.sqrt(Math.pow(down_x-o_x, 2)+Math.pow(down_y-o_y, 2));
			Message msg = new Message();
			msg.what = 0x002;
			msg.obj = String.valueOf(down_x) +";;" +String.valueOf(down_y);
			handlers.sendMessage(msg);
			break;

		}
		case MotionEvent.ACTION_MOVE: {//滑动
			double tilts = Math.sqrt(Math.pow(down_x-o_x, 2)+Math.pow(down_y-o_y, 2));
			if(tilts - tilt >=0){
				 target_x = event.getX();
				 target_y = event.getY();
				 float degree = detaDegree(o_x, o_y, target_x, target_y);
				// 滑过的弧度增量
				float dete = degree - current_degree;
				// 如果小于-90度说明 它跨周了，需要特殊处理350->17,
				if (dete < -270) {
					dete = dete + 360;
					// 如果大于90度说明 它跨周了，需要特殊处理-350->-17,
				} else if (dete > 270) {
					dete = dete - 360;
				}
				Message msg = new Message();
				msg.what = 0x001;
				msg.obj = degree;
				handlers.sendMessage(msg);
				addDegree(dete);
				current_degree = degree;
				postInvalidate();
			}
			break;
		}
		case MotionEvent.ACTION_CANCEL:
		case MotionEvent.ACTION_UP: {//抬起
			// a = a_min;
			up_x = event.getX();
			up_y = event.getY();
			up_degree = detaDegree(o_x, o_y, up_x, up_y);
			 
			Message msg =new Message();
			msg.what = 0x003;
			msg.obj = deta_degree;
			handlers.sendMessage(msg);
			
//			if (speed > 0) {
//				isClockWise = true;
//			} else {
//				isClockWise = false;
//			}
			break;
		}
		}
		return true;
	}

	public float getCurrent_degree() {
		return current_degree;
	}

	/**
	 * 计算以(src_x,src_y)为坐标圆点，建立直角体系，求出(target_x,target_y)坐标与x轴的夹角
	 * 主要是利用反正切函数的知识求出夹角
	 * 
	 * @param src_x
	 * @param src_y
	 * @param target_x
	 * @param target_y
	 * @return
	 */
	float detaDegree(float src_x, float src_y, float target_x, float target_y) {

		float detaX = target_x - src_x;
		float detaY = target_y - src_y;
		double d;
		if (detaX != 0) {
			float tan = Math.abs(detaY / detaX);

			if (detaX > 0) {

				if (detaY >= 0) {
					d = Math.atan(tan);

				} else {
					d = 2 * Math.PI - Math.atan(tan);
				}

			} else {
				if (detaY >= 0) {

					d = Math.PI - Math.atan(tan);
				} else {
					d = Math.PI + Math.atan(tan);
				}
			}

		} else {
			if (detaY > 0) {
				d = Math.PI / 2;
			} else {

				d = -Math.PI / 2;
			}
		}

		return (float) ((d * 180) / Math.PI);
	}

	/**
	 * 一个异常，用来判断是否有rotatbitmap
	 * 
	 * @author sun.shine
	 */
	static class NoBitMapError extends RuntimeException {

		/**
         * 
         */
		private static final long serialVersionUID = 1L;

		public NoBitMapError(String detailMessage) {
			super(detailMessage);
		}

	}


	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		if (rotatBitmap != null) {
			rotatBitmap.recycle();
			rotatBitmap = null;
		}
	}
}
